package com.heima.media.listener;

import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class PublishListener {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAuditService auditService;

    //实例化后自动执行该方法
    @PostConstruct
    public void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //监听redis队列
                //获取一个阻塞队列
                RBlockingDeque<Object> queue = redissonClient.getBlockingDeque("article-publish");
                //获取延时队列
                RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(queue);
                //发送延时消息 参数 1 消息内容  2 延时时间 3 时间单位
                delayedQueue.offer("init", 1, TimeUnit.SECONDS);
                while (true) {
                    try {
                       Object msg = queue.poll(1, TimeUnit.MINUTES);
                        if (msg != null && !msg.equals("init")) {
                            System.out.println("接收到消息：" + msg + new Date());
                            //重新发布文章
                            auditService.audit((WmNews) msg);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

}
